﻿using Angle.Krill.LocalesParser;
using Angle.Krill.SystemConfig;
using Angle.Krill.Utils;
using AntdUI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace Angle.Krill
{
    /// <summary>
    /// AntdUI 文档地址
    /// https://gitee.com/antdui/AntdUI/wikis/%E6%8E%A7%E4%BB%B6/Table 
    /// </summary>
    public partial class Main : ShadowForm
    {
        private MainWindowOptions mainWindowOptions = null;
        private AntdUI.IContextMenuStripItem[] notifyIconRightMenu = null;
        private bool isSystemClose = false;

        public NotifyIcon NotifyIcon
        {
            get
            {
                return this.notifyIcon;
            }
        }

        public DockPanel DockPanel
        {
            get
            {
                return this.dockPanel;
            }
        }

        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case 0x0011:
                    m.Result = (IntPtr)1;
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }

        public Main()
        {
            InitializeComponent();

            this.Initialize();
        }

        private void Initialize()
        {
            this.InitializeSysConfig();

            this.mainWindowOptions = new LocalesParser.LocalesParser().Parser();
            this.windowBar.Text = this.mainWindowOptions.WinTitle;
            this.windowBar.SubText = this.mainWindowOptions.SubTitle;

            this.InitializeMainMenu();

            this.InitializeNotifyIcon();
        }
        /// <summary>
        /// 加载壁纸
        /// </summary>
        private void LoadWallpaper()
        {
            WallpaperInfo wallpaperInfo = SysConfigHelper.Instance.SysConfig?.WallpaperInfo;
            if (wallpaperInfo != null)
            {
                WallpaperHelper.Instance.LoadWallpaper(wallpaperInfo);
            }
        }

        private void InitializeNotifyIcon()
        {
        }

        private void InitializeDockPanel()
        {
            string uiFile = Path.Combine(Application.StartupPath, "Layout.xml");
            if (File.Exists(uiFile))
            {
                DeserializeDockContent ddContent = new DeserializeDockContent(GetContentFromPersistString);
                this.dockPanel.LoadFromXml(uiFile, ddContent);
            }
        }

        private void InitializeSysConfig()
        {
            SysConfigHelper.Instance.LoadSysConfig();
        }

        private void InitializeMainMenu()
        {
            List<LocalesParser.MainMenu> menus = this.mainWindowOptions.MainWindowBar.Menu;
            int endIndex = 120;

            foreach (LocalesParser.MainMenu menu in menus)
            {
                this.windowBar.Controls.Add(this.CreateAntdUIDropdown(menu, ref endIndex));
            }
        }

        private Dropdown CreateAntdUIDropdown(LocalesParser.MainMenu menu, ref int endIndex)
        {
            Dropdown dropdown = new Dropdown
            {
                Text = menu.Title,
                Tag = menu.Tag,
                Name = menu.Tag,
                Anchor = System.Windows.Forms.AnchorStyles.Top | AnchorStyles.Left,
                BackColor = System.Drawing.SystemColors.Control,
                DropDownArrow = true,
                ForeColor = System.Drawing.Color.Black,
                Location = new System.Drawing.Point(endIndex, 0),
                Placement = AntdUI.TAlignFrom.Bottom,
                ShowArrow = true,
                Size = new System.Drawing.Size(menu.Weight, menu.Height),
                Trigger = AntdUI.Trigger.Click,
                Type = AntdUI.TTypeMini.Primary
            };

            dropdown.SelectedValueChanged += Dropdown_SelectedValueChanged;

            endIndex += dropdown.Width;

            if (menu.Sub.Count > 0)
            {
                dropdown.Items.AddRange(this.GetSubMenuItem(menu.Sub));
            }

            return dropdown;
        }

        private void Dropdown_SelectedValueChanged(object sender, object value)
        {
            if (value is SelectItem selectItem)
            {
                LocalesParser.MainMenu menu = selectItem.Tag as LocalesParser.MainMenu;
                if (null == menu)
                {
                    return;
                }
                if (menu.Target == "dock")
                {
                    this.dockPanel.ShowDummyWindow(menu);
                }
                else if (menu.Target == "dialog")
                {
                    if (menu.Tag == "Angle.Krill.Files")
                    {
                        string selectFolderPath = FileHelper.GetOpenFolderPath();
                        if (string.IsNullOrEmpty(selectFolderPath))
                        {
                            return;
                        }
                        this.dockPanel.ShowFilesForm(selectFolderPath);
                    }
                    else
                    {
                        FormHelper.ShowDialog(menu?.Tag?.ToString());
                    }
                }
                else
                {
                }
            }
        }

        /// <summary>
        /// 获取子菜单
        /// </summary>
        /// <param name="menus"></param>
        /// <returns></returns>
        private List<object> GetSubMenuItem(List<LocalesParser.MainMenu> menus)
        {
            List<object> selectItems = new List<object>();

            foreach (LocalesParser.MainMenu sub in menus)
            {
                if (sub.Target == "divider")
                {
                    DividerSelectItem selItem = new DividerSelectItem();
                    selectItems.Add(selItem);
                }
                else
                {
                    SelectItem selItem = new SelectItem(sub.Title, sub);
                    if (null != sub.Sub && sub.Sub.Count > 0)
                    {
                        selItem.Sub = this.GetSubMenuItem(sub.Sub);
                    }

                    if (!string.IsNullOrEmpty(sub.Icon))
                    {
                        var icon = FontAwesomeHelper.Instance.TypeDict[sub.Icon];

                        selItem.Icon = FontAwesomeHelper.Instance.GetImage(icon);
                    }

                    selectItems.Add(selItem);
                }
            }

            return selectItems;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (null != SysConfigHelper.Instance.SysConfig?.MainConfig?.WindowConfig)
            {
                WindowConfig windowConfig = SysConfigHelper.Instance.SysConfig?.MainConfig?.WindowConfig;

                this.Size = new System.Drawing.Size(windowConfig.Width, windowConfig.Height);
                this.Location = new System.Drawing.Point(windowConfig.X, windowConfig.Y);
                this.MinimumSize = new Size(windowConfig.MinWidth, windowConfig.MinHeight);
            }

            this.InitializeDockPanel();
        }

        private IDockContent GetContentFromPersistString(string persistString)
        {
            return DockHelper.GetDockContent(this.dockPanel, persistString);
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!this.isSystemClose)
            {
                bool isClosed = true;

                AntdUI.Modal.open(new AntdUI.Modal.Config(null, "提示", "是否缩小化到托盘", AntdUI.TType.Warn)
                {
                    CancelText = "否",
                    OkText = "是",
                    OnOk = config =>
                    {
                        e.Cancel = true;
                        // 确保在创建控件（Main窗体）的线程上执行UI操作
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new Action(SetMainDisplay));
                        }
                        else
                        {
                            this.notifyIcon.Visible = true;    //显示托盘图标
                            this.Hide();
                        }
                        isClosed = false;

                        return true;
                    }
                });

                if (isClosed && WallpaperHelper.Instance.CurWinWallpaper != null)
                {
                    WallpaperHelper.Instance.CurWinWallpaper.Hide();
                    WallpaperHelper.Instance.CurWinWallpaper.Close();
                    WindowsApiHelper.ReWallpaper();
                }
            }
        }

        private void SetMainDisplay()
        {
            this.notifyIcon.Visible = true;
            this.Hide();
        }

        private void Main_Shown(object sender, EventArgs e)
        {
            this.LoadWallpaper();
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.dockPanel.SaveAsXml(Path.Combine(Application.StartupPath, "Layout.xml"));

            SysConfigHelper.Instance.SaveSysConfig(() =>
                {
                    SysConfigHelper.Instance.SysConfig.MainConfig.WindowConfig = new WindowConfig
                    {
                        Height = this.Size.Height,
                        Width = this.Size.Width,
                        X = this.Location.X,
                        Y = this.Location.Y,
                        MinWidth = 1108,
                        MinHeight = 604,
                    };
                });
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.notifyIcon.Visible = false;
            this.Show();
            this.Activate(); // 激活窗体
        }

        private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                //this.TopMost = true;
                //this.InitializeNotifyIconRightMenu();
                //AntdUI.ContextMenuStrip.open(this, it =>
                //{
                //    if (it.Tag?.ToString() == "ShowForm")
                //    {
                //        this.ShowForm();
                //    }
                //}, this.notifyIconRightMenu);
            }
        }

        private void InitializeNotifyIconRightMenu()
        {
            //if (null != this.notifyIconRightMenu)
            //{
            //    return;
            //}

            //this.notifyIconRightMenu = new AntdUI.IContextMenuStripItem[]
            //{
            //    new AntdUI.ContextMenuStripItem("显示"){
            //        Tag="ShowForm"
            //    },
            //    new AntdUI.ContextMenuStripItemDivider(),
            //    new AntdUI.ContextMenuStripItem("退出","Del"){
            //        Icon = ImageHelper.RemoveIcon,
            //        Tag="Exit"
            //    },
            //};
        }

    }
}
